package cn.sfrog.common.obs;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.sfrog.common.oss.OssProperties;
import cn.sfrog.common.oss.service.OssTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;


@Component
public class OssUtil {

    @Autowired
    private  OssProperties ossProperties;

    @Autowired
    private  OssTemplate ossTemplate;


    public  String uploadFileOss(MultipartFile multipartFile){
        String fileName = IdUtil.simpleUUID() + StrUtil.DOT + FileUtil.extName(multipartFile.getOriginalFilename());
        Map<String, String> resultMap = new HashMap<>(4);
        resultMap.put("bucketName", ossProperties.getBucketName());
        resultMap.put("fileName", fileName);
        resultMap.put("url", String.format("%s/%s/%s", ossProperties.getEndpoint(), ossProperties.getBucketName(), fileName));
        try {
            ossTemplate.putObject(ossProperties.getBucketName(), fileName, multipartFile.getInputStream());
        } catch (Exception e) {
//            log.error("上传失败", e);
//            return AjaxResult.error(e.getLocalizedMessage());
        }
        return String.format("%s/%s/%s", ossProperties.getEndpoint(), ossProperties.getBucketName(), fileName);
    }



}
